using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XLua;

public class LuaManger : Singleton<LuaManger>
{
    public LuaEnv luaenv;

    new
        // Start is called before the first frame update
        void Awake()
    {
        string luaPath;
        if (Const.LOCAL)
        {
            luaPath = Application.dataPath + "/lua/main.lua";
        }
        else
        {
           luaPath = Utils.GetPersistentDataPath(true) + "/AssetBundle/lua/main.lua";
        }
        byte[] luaStr = File.ReadAllBytes(luaPath);
        luaenv = new LuaEnv();
        luaenv.AddBuildin("pb", XLua.LuaDLL.Lua.LoadPb);
        luaenv.DoString(luaStr);
        base.Awake();
    }

    public static LuaTable GetTable(string fullPath)
    {
        return Instance.luaenv.Global.Get<LuaTable>(fullPath);
    }

    public object[] CallFunction(string classname, string funcName, params object[] args)
    {
        LuaTable metatable = luaenv.Global.Get<LuaTable>(classname);
        LuaFunction lnew = null;
        if (metatable != null)
            lnew = (LuaFunction)metatable[funcName];
        if (lnew != null)
        {
            return lnew.Call(metatable, args);
        }
        else
        {
            return null;
        }
    }

    public object[] CallFunction(string funcName, params object[] args)
    {
        LuaFunction lf = luaenv.Global.Get<LuaFunction>(funcName);
        if (lf != null)
        {
            return lf.Call(args);
        }
        else
        {
            return null;
        }
    }

    public void LuaGC()
    {
        luaenv.GC();
    }
}
